<?php

// +----------------------------------------------------------------------
// | Apprh.Shop
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.apprh.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// +----------------------------------------------------------------------
// | Author: 
// +----------------------------------------------------------------------

namespace app\admin\controller;

use controller\BasicAdmin;
use service\LogService;
use service\NodeService;
use service\DesService;
use service\HttpService;
use think\Db;
use think\Request;
use think\Validate;
use think\Controller;

/**
 * 系统登录控制器
 * class Login
 * @package app\admin\controller
 * @author 
 * @date 2017/02/10 13:59
 */
class Login extends BasicAdmin
{

    /**
     * 控制器基础方法
     */
    public function _initialize()
    {
        parent::_initialize();
        if (session('user') && $this->request->action() !== 'out') {
            if($this->request->action() == 'autologin'){
                $this->autologin();
            }
            $this->redirect('@admin');
        }
    }

    //快捷登录
    public function autologin(){
        session('user', null);
        $pesg = $this->request->param('pesg');
        // $formed_pesg  = decrypt($pesg, get_app_auth_key());
        // $des = new DesService(get_app_auth_key(), 'DES-CBC', DesService::OUTPUT_BASE64, 'pedzsw99');
        $root = config('dbx.app_auth_domain').'/uc/api/_get_app_key';
        $app_auth = HttpService::get($root);
        $app_auth = json_decode($app_auth, true);
        // halt($app_auth);
        if($app_auth['code'] == 1){
            $app_auth_key = $app_auth['data'];
        }else{
            flash('error', $app_auth['msg']);
            $this->redirect(url('@admin/login'));            
        }
        $des = new DesService($app_auth_key, 'DES-CBC', DesService::OUTPUT_BASE64, 'pedzsw99');
        $formed_pesg = $des->decrypt($pesg);
        // halt($formed_pesg);
        //pesg验证
        if(!$pesg || !$formed_pesg){
            flash('error', '非法请求!');
            $this->redirect(url('@admin/login'));
        }
        // //远程更新app_auth_key
        // Db::connect(config('dbx.SU'))->name('SystemConfig')->where('name', 'app_auth_key')->update(['value' => md5(uniqid(md5(microtime(true)),true))]);
        $user = $this->SU->where('username', $formed_pesg)->find();
        // halt($user);
        
        if (empty($user)) {
            flash('error', '登录账号不存在，请重试!');
            $this->redirect(url('@admin/login'));
        }

        if (empty($user['status'])) {
            flash('error', '账号已经被禁用，请联系管理!');
            $this->redirect(url('@admin/login'));
        }
        if ($user['is_deleted'] == 1) {
            flash('error', '账号已经被删除，请联系管理!');
            $this->redirect(url('@admin/login'));
        }

        //应用授权
        $chkU = chk_app_auth($user['authorize']);
        if($chkU['code'] == 0){
            flash('error', $chkU['msg']);
            $this->redirect(url('@admin/login'));
        }
        // 更新登录信息
        $data = ['login_at' => time(), 'login_num' => ['exp', 'login_num+1']];
        $this->SU->where(['id' => $user['id']])->update($data);
        session('user', $user);
        !empty($user['authorize']) && NodeService::applyAuthNode();
        LogService::write('系统用户', '用户登录系统成功');
        flash('success', '登录成功，正在进入系统...');
        $this->redirect(url('@admin'));
    }

    public function index()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post()['AdminLoginModel'];
            // $post = $this->request->post();
            // halt($post);
            // 输入数据效验
            $username = trim($post['username']);
            $password = trim($post['password']);
            $verify = trim($post['verify']);
            if (strlen($username) < 4) {
                flash('error', '登录账号长度不能少于6位有效字符!');
                $this->redirect(url('@admin/login'));
            }
            if (strlen($password) < 4) {
                flash('error', '登录密码长度不能少于6位有效字符!');
                $this->redirect(url('@admin/login'));
            }
            // 验证码
            // $verifyCode = $this->request->post('verify', '', 'trim');
            if( !captcha_check($verify) ) {
                // $this->error('验证码不正确');
                flash('error', '验证码不正确!');
                $this->redirect(url('@admin/login'));
            }
            // 用户信息验证
            $user = $this->SU->where('username', $username)->find();
            if (empty($user)) {
                flash('error', '登录账号不存在，请重新输入!');
                $this->redirect(url('@admin/login'));
            }
            if (($user['password'] !== md5($password))) {
                flash('error', '登录密码与账号不匹配，请重新输入!');
                $this->redirect(url('@admin/login'));
            }
            if (empty($user['status'])) {
                flash('error', '账号已经被禁用，请联系管理!');
                $this->redirect(url('@admin/login'));
            }
        if ($user['is_deleted'] == 1) {
            flash('error', '账号已经被删除，请联系管理!');
            $this->redirect(url('@admin/login'));
        }

            // //应用授权
            // $chkU = chk_app_auth($user['authorize']);
            // // halt($chkU);
            // if($chkU['code'] == 0){
            //     flash('error', $chkU['msg']);
            //     $this->redirect(url('@admin/login'));
            // }
            
            // 更新登录信息
           $data = ['login_at' => time(), 'login_num' => ['exp', 'login_num+1']];
            $this->SU->where(['id' => $user['id']])->update($data);
            session('user', $user);
            // //添加地区session
            // $contr = new Alleviationdynamic();
            // $attf_area_id = $user['fp_affiliated_area'];
            // if($attf_area_id == 0){
            //     $attf_area_id = 1;
            // }
            // $_areaList = Db::name('fp_area')->where(['id'=>$attf_area_id])->order('id asc')->select();
            // $_areaList = $contr->dzTreeCategory('fp_area',$_areaList);
            // $areaIds = $contr->areaIds($_areaList);
            // session('areaIds', $areaIds);
            !empty($user['authorize']) && NodeService::applyAuthNode();
            LogService::write('系统用户', '用户登录系统成功');
            flash('success', '登录成功，正在进入系统...');
            $this->redirect(url('@admin'));
        }else{
            return $this->fetch('', ['title' => '用户登录']);
        }
    }

    /**
     * 退出登录
     */
    public function out()
    {
        LogService::write('系统用户', '用户退出系统成功');
        session('user', null);
        // session_destroy();
        $this->success('退出登录成功！', '@admin/login');
    }

    public function verify_code(){
		ob_clean();
        if (is_mobile()){
            $array = array(
                'imageW' => 80,
                'imageH' => 39,
                'length' => 4,
                'fontSize'=>12,
                // 是否画混淆曲线
                'useNoise' => false,
                'useCurve' => false,
            );
        }else{
            $array = array(
                'imageW' => 180,
                // 'imageH' => 38,
                'length' => 4,
                'fontSize'=>24,
                // 是否画混淆曲线
                'useNoise' => false,
                'useCurve' => false,
            );
        }


        return captcha("", $array);
    }
}
